/** Access Cheval DB through thin driver, and introduce ResultSetMetaData class.
	1. Download thin JDBC driver from Oracle.
	2. ResultSetMetaData interface is implemented by driver provider. The meta data
	   provide methods for accessing properties of table columns such as
		-- nnumber of columns, column names and types,
		-- precision and scale
		-- is column readable, writable, searchable and etc.
    The example uses meta data to access number of column of result set and column
headings of a result set.
*/

import java.sql.*;
import java.io.*;

public class AccessProverDB2 {

	Connection cnn;
	Statement  stmt;
	ResultSet  res;
	ResultSetMetaData meta;

	String url = "jdbc:oracle:thin:@prover.cs.csubak.edu:1521:PROVERDB",
		 user="gradebook", passwd="c3m4p2s";

	public AccessProverDB2() {
	   try {
               // Class.forName(driverName);
		DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
		cnn = DriverManager.getConnection(url, user, passwd);
		stmt = cnn.createStatement();
	   } catch (SQLException e ) { e.printStackTrace(); System.exit(-1); }
	}

	public static void main(String argv[]) {
		AccessProverDB2 ex2 = new AccessProverDB2(); // get connected, and create stmt.
		byte ans[] = new byte[120];
		char c = ' ';
		String	sql;

		while ( true ) {
			for ( int i = 0; i < ans.length; i ++ ) ans[i] = (byte) ' ';
			sql = ScreenIO.promptForString("Enter a SQL statement or Q/e to quite ... ");
			if ( sql == null || sql.equals("") ) continue;
			try { c = sql.charAt(0); } catch (StringIndexOutOfBoundsException e) {}
			if ( c == 'q' || c == 'Q' ) System.exit(0);
			ex2.executeSQL(sql);
			ex2.displayResultSet();
		}
	}

	void executeSQL(String sql) {
	   try {
		System.out.println("\n");
		res = stmt.executeQuery(sql);
		meta = res.getMetaData();
	   } catch (SQLException e) { e.printStackTrace(); }
	}

	void displayResultSet() {
	   try {
		int colCnt = meta.getColumnCount();
		displayColumnHeaders(colCnt);
		while ( res.next() ) {
			for ( int i = 1; i <= colCnt; i ++ )
				System.out.print(ScreenIO.expandString( res.getString(i), 15 )) ;
			System.out.println();
		}	
	   } catch (SQLException e) { e.printStackTrace();  /*System.exit(-1);*/ }
	     catch (NullPointerException e ) { e.printStackTrace(); }

	}

	void displayColumnHeaders(int cnt) {
	   try {
		for ( int i = 1; i <= cnt; i ++ )
			System.out.print( ScreenIO.expandString(meta.getColumnName(i), 15 ));
		System.out.println();

		for ( int i = 1; i <= cnt; i ++ )
			System.out.print( ScreenIO.expandString("===========", 15 ));
		System.out.println();
	   } catch (SQLException e ) {}
	}

	protected void finalize() {
	   try { stmt.close(); res.close(); cnn.close(); } catch (SQLException e) {}
	}
}
